﻿package main

import (
	"html/template"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{} // use default option

func init() {
	// init tcp bridge port
	bridge := TcpBridgeHandler{
		ClientNodes: make(map[int]*TcpBridgeNode),
		tcpServer:   nil,
	}
	go bridge.tcpBridgeRun(":9000")

	log.Println("=========================================")
	log.Println("Test Http Server:\t 0.0.0.0:8080  <= visit it")
	log.Println("Bridge Server:\t 0.0.0.0:9000  <= just for client connect")
	log.Println("Bridge For Client Server:\t 0.0.0.0:50010  <= visit it")
	log.Println("=========================================\r\n")
}

func main() {
	r := gin.New()

	// proxy setting for subdomain to tcp:port address
	// r.Use(proxyMiddleware)

	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "hello world 1",
		})
	})
	r.GET("/abc", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "ABC abc 123",
		})
	})
	r.GET("/test", func(c *gin.Context) {
		homeTemplate.Execute(c.Writer, "ws://"+c.Request.Host+"/ws")
	})

	r.GET("/ws", func(ctx *gin.Context) {
		w, r := ctx.Writer, ctx.Request
		c, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Println("upgrade:", err)
			return
		}
		defer c.Close()
		for {
			mt, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				break
			}
			log.Printf("recv:%s", message)
			err = c.WriteMessage(mt, message)
			if err != nil {
				log.Println("write:", err)
				break
			}
		}
	})

	// run web server
	r.Run(":8080")
}

// func proxyMiddleware(context *gin.Context) {
// 	hostParams := strings.Split(context.Request.Host, ".")
// 	// 针对 x.proxy.test.com的域名，进行upstream proxy
// 	if len(hostParams) > 3 && strings.HasSuffix(context.Request.Host, ".proxy.test.com") {
// 		u, _ := url.Parse("http://127.0.0.1:50010")
// 		proxy := httputil.NewSingleHostReverseProxy(u)
// 		proxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, e error) {
// 			writer.WriteHeader(http.StatusBadGateway)
// 		}
// 		proxy.ServeHTTP(context.Writer, context.Request)
// 		return
// 	}
// 	context.Next()
// }

var homeTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>  
window.addEventListener("load", function(evt) {
    var output = document.getElementById("output");
    var input = document.getElementById("input");
    var ws;
    var print = function(message) {
        var d = document.createElement("div");
        d.textContent = message;
        output.appendChild(d);
        output.scroll(0, output.scrollHeight);
    };
    document.getElementById("open").onclick = function(evt) {
        if (ws) {
            return false;
        }
        ws = new WebSocket("{{.}}");
        ws.onopen = function(evt) {
            print("OPEN");
        }
        ws.onclose = function(evt) {
            print("CLOSE");
            ws = null;
        }
        ws.onmessage = function(evt) {
            print("RESPONSE: " + evt.data);
        }
        ws.onerror = function(evt) {
            print("ERROR: " + evt.data);
        }
        return false;
    };
    document.getElementById("send").onclick = function(evt) {
        if (!ws) {
            return false;
        }
        print("SEND: " + input.value);
        ws.send(input.value);
        return false;
    };
    document.getElementById("close").onclick = function(evt) {
        if (!ws) {
            return false;
        }
        ws.close();
        return false;
    };
});
</script>
</head>
<body>
<table>
<tr><td valign="top" width="50%">
<p>Click "Open" to create a connection to the server, 
"Send" to send a message to the server and "Close" to close the connection. 
You can change the message and send multiple times.
<p>
<form>
<button id="open">Open</button>
<button id="close">Close</button>
<p><input id="input" type="text" value="Hello world!">
<button id="send">Send</button>
</form>
</td><td valign="top" width="50%">
<div id="output" style="max-height: 70vh;overflow-y: scroll;"></div>
</td></tr></table>
</body>
</html>
`))
